<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click="hAdd">新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="list">
              <el-table-column type="index" label="序号" width="120" />
              <el-table-column prop="name" label="角色名称" width="240" />
              <el-table-column prop="description" label="描述" />
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button size="small" type="success" @click="hAssignPerm(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="del(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination background :current-page="q.page" :page-size="q.pagesize" layout="total,  prev, pager, next, jumper" :total="total" @current-change="hCurrentChange" />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!--新增和编辑的dialog -->
      <el-dialog :title="isEdit ? '编辑弹层' : '添加弹层'" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="showDialog" @closed="hClose">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="showDialog = false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <!-- 分配权限dialog -->
      <el-dialog v-if="showDialogAssign" title="分配权限弹层" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="showDialogAssign">
        <assign-permissions :current-id="currentId" @cancel="hCancel" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { addRole, editRole, getAllRole, removeRole } from '@/api/role'
import assignPermissions from '@/views/settings/assignPermissions.vue'
export default {
  name: 'Role',
  components: { assignPermissions },

  data() {
    return {
      q: {
        page: 1,
        pagesize: 5
      },
      currentId: '',
      total: 0,
      list: [],
      showDialog: false,
      showDialogAssign: false,
      roleForm: {
        name: '',
        description: '',
        state: 0
      },
      // isEdit是true是编辑的弹层，false是添加的弹层
      isEdit: false,
      // dialog的校验规则
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      }
    }
  },

  created() {
    this.loadGetRole()
  },

  methods: {
    // 获取所有的角色
    async loadGetRole() {
      try {
        const { data } = await getAllRole(this.q)
        // console.log(data)
        this.list = data.rows
        this.total = data.total
      } catch (error) {
        console.log(error)
      }
    },
    // 删除角色
    async del(id) {
      // 提示用户是否要删除
      const re = await this.$confirm('您确认要删除吗?', '提示', {
        type: 'warning'
      }).catch(e => e)
      // console.log(re)
      if (re === 'cancel') return
      try {
        // 发请求去删除角色
        const res = await removeRole(id)
        // 根据结果提示用户
        this.$message.success(res.message)
        // 要先判断是不是当前的最后一条
        if (this.list.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        // 从新渲染页面
        this.loadGetRole()
        // console.log(res)
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    // dialog点击确认
    async hSubmit() {
      // 兜底校验
      await this.$refs.roleForm.validate()
      try {
        // 如果是编辑则发编辑的请求，否则发添加的请求
        let res = null
        if (this.isEdit) {
          res = await editRole(this.roleForm)
        } else {
          // 发请求
          res = await addRole(this.roleForm)
          // 新增的数据要在最后一页显示
          // 如果刚好满一页，total要加1
          if (this.total % this.q.pagesize === 0) {
            this.total++
          }
          this.q.page = Math.ceil(this.total / this.q.pagesize)
        }
        // console.log(res)
        // 提示用户
        this.$message.success(res.message)

        // 从新渲染
        this.loadGetRole()
        // 关闭dialog
        this.showDialog = false
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 关闭dialog的函数
    hClose() {
      // 重置表单
      // 扩展知识: 该方法只会重置有 prop 的表单项 (字段)
      this.$refs.roleForm.clearValidate()
      this.roleForm = {
        name: '',
        description: '',
        state: 0
      }
      // 关闭弹层
      this.showDialog = false
    },
    // 编辑按钮
    hEdit(row) {
      // console.log(row)
      this.roleForm = { ...row }
      this.showDialog = true
      this.isEdit = true
    },
    // 点击新增角色
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    hCurrentChange(val) {
      this.q.page = val
      this.loadGetRole()
    },
    // 关闭分配权限的dialog
    hCancel() {
      this.showDialogAssign = false
    },
    // 点击分配权限
    async hAssignPerm(id) {
      this.showDialogAssign = true
      this.currentId = id
    }
  }
}
</script>
